﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Linq;

namespace DotNetCommon.Extensions
{
    /// <summary>
    /// DataTable扩展类
    /// </summary>
    public static class DataTableExtensions
    {
        /// <summary>
        /// 将DataTable转为实体类集合，如果DataTable为null则返回空集合
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static List<T> ToModels<T>(this DataTable dt) where T : class, new()
        {
            var list = dt.ToDictionaryList();
            return list.ToModels<T>();
        }

        /// <summary>
        /// 将DataTable的第一行转为单个实体类
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static T ToModelFirstOrDefault<T>(this DataTable dt) where T : class, new()
        {
            var len = dt.Rows.Count;
            if (len == 0) return default(T);
            if (len > 1)
            {
                var newDt = dt.Clone();
                var row = newDt.NewRow();
                for (int i = 0, len2 = newDt.Columns.Count; i < len2; i++)
                {
                    row[i] = dt.Rows[0][i];
                }
                newDt.Rows.Add(row);
                return ToModelFirstOrDefault<T>(newDt);
            }
            return ToModels<T>(dt).FirstOrDefault();
        }

        /// <summary>
        /// 将DataTable转换为字典集合，如果DataTable为null则返回空集合
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static List<Dictionary<string, object>> ToDictionaryList(this DataTable dt)
        {
            var cols = new List<string>();
            var list = new List<Dictionary<string, object>>();
            if (dt == null) return list;
            for (int i = 0, count = dt.Columns.Count; i < count; i++) cols.Add(dt.Columns[i].ColumnName);
            for (int i = 0, count = dt.Rows.Count; i < count; i++)
            {
                var dic = new Dictionary<string, object>();
                foreach (var col in cols)
                {
                    dic[col] = dt.Rows[i][col];
                }
                list.Add(dic);
            }
            return list;
        }

    }
}
